# -*- coding: utf-8 -*-
import json
import logging

from future.utils import raise_with_traceback

from django.views.decorators.http import require_GET, require_POST
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator

from api.preset.handler import get_fixed_bucket
from api.show.logic import (view_my_shows, view_shows_timeline)

from common.show.model import AnnounceShow, SHOW_STATUS
from common.show import db as show_db

from common.utils.exceptions import DataError
from common.utils.api import token_required, check_params
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError, AuthenticateError
from common.lottery.db import get_order_index
from common.lottery.cyclical import ORDER_STATUS
from api.show.logic import _create_show_lite

_LOGGER = logging.getLogger('bigbang')
_DEFAULT_PAGE_SIZE = 20


class SingleShow(TemplateView):

    def get(self, req, show_id):
        """
        获取晒单详情
        """
        try:
            show_id = int(show_id)
            show = show_db.get_show_by_id(show_id)
        except Exception as e:
            raise_with_traceback(ParamError(e))
        show_detail = _create_show_lite(show)
        return show_detail

    @method_decorator(token_required)
    def post(self, req, show_id):
        """
        更新晒单
        """
        try:
            show_id = int(show_id)
            info = json.loads(req.body)
        except Exception as e:
            raise_with_traceback(ParamError(e))
        check_params(info, ['images', 'content'])

        show = show_db.get_show_by_id(show_id)
        if not show or (show.user_id != req.user_id):
            raise AuthenticateError('not access')
        images = get_fixed_bucket(info['images'], bucket='show', disable_domain=True)
        show_db.update_show(show_id, info['content'], info['images'])

        return {}

    @method_decorator(response_wrapper)
    def dispatch(self, *args, **kwargs):
        return super(SingleShow, self).dispatch(*args, **kwargs)


@require_GET
@response_wrapper
@token_required
def get_my_shows(request):
    """
    查看我的晒单记录
    """
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
    except Exception as e:
        raise_with_traceback(ParamError(e))

    s_list = view_my_shows(request.user_id, page, size)
    data = {
        'list': s_list,
        'page': page if page > 0 else 1,
        'size': len(s_list)
    }
    return data


@require_GET
@response_wrapper
def get_timeline(request):
    """
    获取晒单分享
    """
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
    except Exception as e:
        raise_with_traceback(ParamError(e))

    s_list = view_shows_timeline(page, size)
    data = {
        'list': s_list,
        'size': len(s_list)
    }
    return data
